#include "hitpoint.h"
#include "images_diffuse.h"
#include "random.h"
#include "tag.h"
#include "sounds.h"

declare_body(hitpoint, {
	vec offset;
});
declare_tick(hitpoint, { })
declare_draw(hitpoint, { })
declare_head(hitpoint)

declare_body(explode, {
	size_t life;
});
declare_tick(explode, { if(--self->life == 0) return 1; })
declare_draw(explode, { })
declare_head(explode)

void explosion(vec location) {
	entity *ent = ent_new();
	ent->position = location;
	
	add_component(ent, get_animator_c(&sprite_explosion, 2, vxy(16.f, 16.f)));
	
	explode *e = c_new(explode);
	e->life = 9 * 2;
	add_component(ent, e);
}

void add_hitpoint(entity *e, vec offset) {
	hitpoint *h = c_new(hitpoint);
	h->offset = vadd(offset, vxy(rand_range(-1, 1), rand_range(-1, 1)));
	add_component(e, h);
}

void add_hitpoint_t(entity *e, vec offset, int threshold, int actual) {
	if(actual >= threshold) add_hitpoint(e, offset);
}

void remove_hitpoint(entity *e) {
	hitpoint *h = get_component(e, hitpoint);
	if(!h) {
		for(size_t i = 0; i < 3; ++i)
			explosion(vadd(e->position, vxy(rand_range(-5, 5), rand_range(-5, 5))));
		if(e->tag == TAG_PLAYER) {
			level_lost();
			play_sound(s_enemy_explode);
		}
		else {
			play_sound(s_enemy_explode);
			ent_destroy(e);
		}
		return;
	}
	
	if(e->tag == TAG_ENEMY) {
		play_sound(s_enemy_hit);
	}
	else play_sound(s_player_hit);
	
	vec offset = h->offset;
	add_component(e, get_animator_c(&sprite_fire, 1, vsub(vxy(1.5f, 0.f), offset)));
	remove_component(e, h);
}